package com.arpa.wms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.TipConst;
import com.arpa.wms.domain.dto.CollectDTO;
import com.arpa.wms.domain.dto.CollectExcelDTO;
import com.arpa.wms.domain.entity.Collect;
import com.arpa.wms.domain.enums.CollectStatusEnum;
import com.arpa.wms.domain.vo.CollectVO;
import com.arpa.wms.service.ICollectService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 领用单 controller
 * @author jinss
 * @date 2020-08-28 13:25:40
 **/
@Api(tags = "领用单")
@RestController
@RequestMapping(value="/collect", produces = "application/json;charset=UTF-8")
@Log4j2
public class CollectController {

   @Autowired
   private ICollectService collectService;

    /**
     * 获取 领用单 列表
     * @param collectDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 领用单 列表", notes = "获取 领用单 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = CollectVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(CollectDTO collectDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录账号授权的仓库过滤
            collectDTO.setWarehouseCodes(authMap.get(CommonConst.WAREHOUSE_CODES));
            //登录账号授权的货主过滤
            collectDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            collectDTO.setGroupCode(UserUtil.getBranchCode());
            CollectVO collectVosum = collectService.queryListSum(collectDTO);
            List<CollectVO> collectVOList = collectService.queryList(collectDTO);

            Page returnPage = new Page(collectDTO.getPageNum(), collectDTO.getPageSize());
            returnPage.setRecords(collectVOList);
            returnPage.setTotal(collectVosum.getTotal());
            returnPage.setSumObject(collectVosum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 领用单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 领用单 ", notes = "添加 领用单 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody @Validated(Collect.Save.class) Collect entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            collectService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改 领用单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "修改领用单", notes = "修改领用单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(Collect.Update.class) Collect entity, HttpServletRequest request) {
        int updateNum = collectService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:" + entity.getCode());
        }else{
            return Result.ok("修改成功,更新" + updateNum + "条数据！");
        }
    }

    /**
     * 审核 领用单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "审核领用单", notes = "审核领用单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/audit")
    public Result audit(@RequestBody @Validated(Collect.Audit.class) Collect entity, HttpServletRequest request) {
        if(StrUtil.isBlank(entity.getCode())){
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        int updateNum = collectService.audit(entity);
        if(updateNum == 0){
            return Result.error(entity.getCode() + "审核失败!");
        }else{
            return Result.ok(entity.getCode() + "审核成功!");
        }
    }

    /**
     * 作废领用单
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "作废领用单", notes = "作废领用单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/invalid")
    public Result invalid(@RequestParam String code, HttpServletRequest request) {
        if(StrUtil.isBlank(code)){
            return Result.error("code不能为空");
        }
        int updateNum = collectService.updateStatusByCode(code, CollectStatusEnum.INVALID.getValue());
        if(updateNum == 0){
            return Result.error(code + "作废失败!");
        }else{
            return Result.ok(code + "作废成功!");
        }
    }

    /**
     * 获取领用单详情
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取领用单详情", notes = "获取领用单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "领用单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Collect.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result collect(@PathVariable String code, HttpServletRequest request) {
        try {
            CollectVO entity = collectService.getOneByCode(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "领用 导入 预览", notes = "领用 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/collectView")
    public Result initializationView(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<CollectExcelDTO> list = EasyExcelUtil.read(url.openStream(), CollectExcelDTO.class,2);
            if(CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<CollectExcelDTO> collectExcelDTOList = collectService.collectView(list);
            return new Result().data(collectExcelDTOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    @ApiOperation(value = "领用 导入", notes = "领用 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/collectImport")
    public Result initializationImport(HttpServletRequest request) {
        try {
            collectService.collectImport();
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

 }
